// .........................................................................
// Title: firm_regressions.do
//
// Estimates firm-level regressions with a range of firm outcomes, both
// for investment and for offering dynamics
// .........................................................................

* ----------------------------------------------------
* Aggregating objects to firm level
* ----------------------------------------------------

* Add parent firm IDs to security-level sample
use "$tmp/security_iv_sample", clear
mmerge cusip using "$tmp/cusip_to_up_firm_id", unmatched(m)
drop _merge
save "$tmp/security_iv_sample_fid", replace

* Aggregate instrument to firm level
use "$tmp/security_iv_sample_fid", clear
keep if event == "gr"
gcollapse (mean) instrument_norm [aw = value_outstanding], by(firm_id)
drop if missing(instrument_norm)
save "$tmp/firm_instrument", replace

* Average duration at firm level
use "$tmp/holdings_mf_ins_issuance_trace_universe_refined", clear
keep if date_q == tq(2007q1)
mmerge cusip using "$tmp/cusip_to_up_firm_id", unmatched(m)
assert _merge == 3
mmerge cusip date_q using "$tmp/duration_merged_q", unmatched(m)
gcollapse (mean) avg_firm_duration=duration_y [aw = value_outstanding], by(firm_id)

* Construct duration categories
drop if missing(avg_firm_duration)
gen firm_drn_bucket = ""
replace firm_drn_bucket = "0-1" if ~missing(avg_firm_duration) & avg_firm_duration <= 1
replace firm_drn_bucket = "1-3" if ~missing(avg_firm_duration) & avg_firm_duration > 1 & avg_firm_duration <= 3
replace firm_drn_bucket = "3-5" if ~missing(avg_firm_duration) & avg_firm_duration > 3 & avg_firm_duration <= 5
replace firm_drn_bucket = "5-10" if ~missing(avg_firm_duration) & avg_firm_duration > 5 & avg_firm_duration <= 10
replace firm_drn_bucket = "10-15" if ~missing(avg_firm_duration) & avg_firm_duration > 10 & avg_firm_duration <= 15
replace firm_drn_bucket = "15-20" if ~missing(avg_firm_duration) & avg_firm_duration > 15 & avg_firm_duration <= 20
replace firm_drn_bucket = "20+" if ~missing(avg_firm_duration) & avg_firm_duration > 20
save "$tmp/firm_level_duration_gr", replace

* ----------------------------------------------------
* Investment dynamics estimates
* ----------------------------------------------------

* Panel specification
local min_year = 2004
local max_year = 2011

* Controls specification
local controls = "i.leverage_decile#i.year i.size_decile#i.year i.naics2#i.year i._issuer_rating_cat_pm#i.year i._firm_drn_bucket#i.year"

* Construct estimation sample
use "$tmp/consolidated_inv_sample", clear
cap drop post
gen post = 0
replace post = 1 if year >= 2008

mmerge firm_id using "$tmp/firm_instrument", unmatched(m)
mmerge firm_id using "$tmp/firm_level_duration_gr", unmatched(m)
drop _merge

encode firm_drn_bucket, gen(_firm_drn_bucket)
encode issuer_rating_cat, gen(_issuer_rating_cat)
encode issuer_rating_cat_pm, gen(_issuer_rating_cat_pm)

forval year = `min_year'/`max_year' {
    gen share_`year' = share_ins_issuance if year == `year'
    replace share_`year' = 0 if year != `year'
    gen instr_`year' = instrument_norm if year == `year'
    replace instr_`year' = 0 if year != `year'
}
rename share_ins_issuance _share_ins_issuance
rename share_2007 _share_2007 // Excluded dummies for 2007
rename instr_2007 _instr_2007
save "$tmp/consolidated_inv_sample_iv", replace

* Save covariates only
use "$tmp/consolidated_inv_sample_iv", clear
keep firm_id profitability_decile leverage_decile size_decile naics2 issuer_rating_cat* instrument_norm avg_firm_duration firm_drn_bucket _firm_drn_bucket _issuer_rating_cat*
duplicates drop
save "$tmp/up_sample_covariates", replace

* Dynamic DiD: capx
use "$tmp/consolidated_inv_sample_iv", clear
ivreghdfe capx_at (share* = instr_*), absorb(firm_id year `controls') cluster(firm_id)

* Store capx results
gen _year = .
gen _beta = .
gen _sderr = .
gen _beta_aqc = .
gen _se_aqc = .
local i = 1
forval year = `min_year'/`max_year' {
    cap {
        local beta = _b[share_`year']
        local se = _se[share_`year']
        replace _year = `year' if _n == `i'
        replace _beta = `beta' if _n == `i'
        replace _sderr = `se' if _n == `i'
        local i = `i' + 1
    }
}

* Dynamic DiD: capx-acq
ivreghdfe capx_aqc_at (share* = instr_*), absorb(firm_id year `controls') cluster(firm_id)

* Store capx-aqc results
local i = 1
forval year = `min_year'/`max_year' {
    cap {
        local beta = _b[share_`year']
        local se = _se[share_`year']
        replace _beta_aqc = `beta' if _n == `i'
        replace _se_aqc = `se' if _n == `i'
        local i = `i' + 1
    }
}
keep _*
drop if missing(_year)
rename _* *
save "$tmp/investment_dynamics_estimates", replace

* ----------------------------------------------------
* Issuance dynamics estimates
* ----------------------------------------------------

* Get sample
use "$tmp/consolidated_issuance_sample", clear
mmerge firm_id using "$tmp/up_sample_covariates", unmatched(m)
drop if year > `max_year'
drop if year < `min_year'

* Interacted regressors
forval year = `min_year'/`max_year' {
    cap drop share_`year'
    gen share_`year' = share_ins_issuance if year == `year'
    replace share_`year' = 0 if year != `year'
    gen instr_`year' = instrument_norm if year == `year'
    replace instr_`year' = 0 if year != `year'
}

cap drop _beta _sderr _share_ins_issuance _share_2007
gen _year = .
gen _beta = .
gen _sderr = .

rename share_ins_issuance _share_ins_issuance
rename share_2007 _share_2007 // Excluded dummies for 2007
rename instr_2007 _instr_2007

* Dynamic DiD: new issuance
ivreghdfe issuance_indicator (share* = instr_*), absorb(firm_id year `controls') cluster(firm_id)

* Store results
local i = 1
forval year = `min_year'/`max_year' {
    cap {
        local beta = _b[share_`year']
        local se = _se[share_`year']
        replace _year = `year' if _n == `i'
        replace _beta = `beta' if _n == `i'
        replace _sderr = `se' if _n == `i'
        local i = `i' + 1
    }
}
keep _*
drop if missing(_year)
rename _* *
save "$tmp/issuance_dynamics_estimates", replace

* ----------------------------------------------------
* Offering yield dynamics estimates
* ----------------------------------------------------

* Get sample
use "$tmp/consolidated_off_yields_sample", clear
mmerge firm_id using "$tmp/up_sample_covariates", unmatched(m)
drop if year > `max_year'
drop if year < `min_year'

forval year = `min_year'/`max_year' {
    cap drop share_`year'
    gen share_`year' = share_ins_issuance if year == `year'
    replace share_`year' = 0 if year != `year'
    gen instr_`year' = instrument_norm if year == `year'
    replace instr_`year' = 0 if year != `year'
}

cap drop _beta _sderr _share_ins_issuance _share_2007
gen _year = .
gen _beta = .
gen _sderr = .

rename share_ins_issuance _share_ins_issuance
rename share_2007 _share_2007 // Excluded dummies for 2007
rename instr_2007 _instr_2007

* Dynamic DiD: offering yields
ivreghdfe offering_yield (share_* = instr_*), absorb(firm_id year `controls') cluster(firm_id)

* Store results
local i = 1
forval year = `min_year'/`max_year' {
    cap {
        local beta = _b[share_`year']
        local se = _se[share_`year']
        replace _year = `year' if _n == `i'
        replace _beta = `beta' if _n == `i'
        replace _sderr = `se' if _n == `i'
        local i = `i' + 1
    }
}
keep _*
drop if missing(_year)
rename _* *
save "$tmp/offering_yield_dynamics_estimates", replace

* ----------------------------------------------------
* Static DiD regressions
* ----------------------------------------------------

* Construct static regressions sample
use "$tmp/consolidated_inv_sample_iv", clear
keep if inrange(year, 2004, 2011)
mmerge firm_id using "$tmp/up_shares_maturing", unmatched(m)
cap drop instrument_post

gen treat_post = _share_ins_issuance * post / 100
gen instrument_post = instrument_norm * post
gen treat_post_mat = _share_ins_issuance * post * share_maturing / 100

foreach var of varlist capx capx_at leverage_decile size_decile naics2 _firm_drn_bucket _issuer_rating_cat_pm instrument_norm firm_id _share_ins_issuance share_maturing {
    drop if missing(`var')
}
count
local n_obs = r(N)
unique firm_id
local n_firms = r(unique)
save "$tmp/static_firm_reg_sample", replace

* Controls spec
local stat_controls = "i.leverage_decile#i.post i.size_decile#i.post i.naics2#i.post i._issuer_rating_cat_pm#i.post i._firm_drn_bucket#i.post"

* Specification: capx, iv
use "$tmp/static_firm_reg_sample", clear
ivreghdfe capx_at (treat_post = instrument_post), absorb(firm_id year `stat_controls') cluster(firm_id) resid
predict ys, xbd
qui corr ys capx_at
clear
set obs 1
gen reg_order = 1
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen estimator = "IV"
gen outcome = "CAPX"
gen R2 = `r(rho)' ^ 2
gen F = `e(rkf)' 
tempfile static_reg_result1
save `static_reg_result1', replace

* Specification: capx, ols
use "$tmp/static_firm_reg_sample", clear
reghdfe capx_at treat_post, absorb(firm_id year `stat_controls') cluster(firm_id)
clear
set obs 1
gen reg_order = 2
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen estimator = "OLS"
gen outcome = "CAPX"
gen R2 = `e(r2)'
gen F = .
tempfile static_reg_result2
save `static_reg_result2', replace

* Specification: capx, ols, maturing interaction
use "$tmp/static_firm_reg_sample", clear
reghdfe capx_at treat_post treat_post_mat, absorb(firm_id year `stat_controls') cluster(firm_id)
clear
set obs 1
gen reg_order = 3
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen gamma = _b[treat_post_mat]
gen se_gamma = _se[treat_post_mat]
gen estimator = "OLS"
gen outcome = "CAPX"
gen R2 = `e(r2)'
gen F = .
tempfile static_reg_result3
save `static_reg_result3', replace

* Specification: capx-a, iv
use "$tmp/static_firm_reg_sample", clear
ivreghdfe capx_aqc_at (treat_post = instrument_post), absorb(firm_id year `stat_controls') cluster(firm_id) resid
predict ys, xbd
qui corr ys capx_aqc_at
clear
set obs 1
gen reg_order = 4
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen estimator = "IV"
gen outcome = "CAPX-A"
gen R2 = `r(rho)' ^ 2
gen F = `e(rkf)' 
tempfile static_reg_result4
save `static_reg_result4', replace

* Specification: capx-a, ols
use "$tmp/static_firm_reg_sample", clear
reghdfe capx_aqc_at treat_post, absorb(firm_id year `stat_controls') cluster(firm_id)
clear
set obs 1
gen reg_order = 5
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen estimator = "OLS"
gen outcome = "CAPX-A"
gen R2 = `e(r2)'
gen F = .
tempfile static_reg_result5
save `static_reg_result5', replace

* Specification: capx-a, ols, maturing interaction
use "$tmp/static_firm_reg_sample", clear
reghdfe capx_aqc_at treat_post treat_post_mat, absorb(firm_id year `stat_controls') cluster(firm_id)
clear
set obs 1
gen reg_order = 6
gen beta = _b[treat_post]
gen se = _se[treat_post]
gen gamma = _b[treat_post_mat]
gen se_gamma = _se[treat_post_mat]
gen estimator = "OLS"
gen outcome = "CAPX-A"
gen R2 = `e(r2)'
gen F = .
tempfile static_reg_result6
save `static_reg_result6', replace

* Append the results
clear
append using `static_reg_result1'
append using `static_reg_result2'
append using `static_reg_result3'
append using `static_reg_result4'
append using `static_reg_result5'
append using `static_reg_result6'
gen n_obs = `n_obs'
gen n_firms = `n_firms'
gen firm_fe = "Yes"
gen time_fe = "Yes"
gen controls = "Yes"
sort reg_order
order reg_order outcome beta se gamma se_gamma firm_fe time_fe controls n_obs n_firms R2 estimator F
save "$tmp/static_regs", replace

* ----------------------------------------------------
* Format static estimates table for display (Table 6)
* ----------------------------------------------------
use "$tmp/static_regs", clear
foreach var of varlist beta se gamma se_gamma R2 {
    tostring `var', replace force format(%3.2f)
}
tostring F, replace force format(%3.1f)
tostring n_obs, replace
tostring n_firms, replace
drop reg_order outcome
sxpose, clear

rename _var1 CAPX_1
rename _var2 CAPX_2
rename _var3 CAPX_3
rename _var4 CAPX_Acquisitions_4
rename _var5 CAPX_Acquisitions_5
rename _var6 CAPX_Acquisitions_6

gen Field = ""
order Field
replace Field = "Beta" if _n == 1
replace Field = "SE (Beta)" if _n == 2
replace Field = "Gamma" if _n == 3
replace Field = "SE (Gamma)" if _n == 4
replace Field = "Firm FE" if _n == 5
replace Field = "Time FE" if _n == 6
replace Field = "Controls" if _n == 7
replace Field = "Observations" if _n == 8
replace Field = "Firms" if _n == 9
replace Field = "R2" if _n == 10
replace Field = "Estimator" if _n == 11
replace Field = "First Stage F" if _n == 12
foreach var of varlist * {
    replace `var' = "--" if `var' == "."
}

save "$tables/investment_out.dta", replace
export delimited "$tables/investment_out.txt", noquote delimiter(tab) replace
